import axios from 'axios';
import fs from 'fs';
import path from 'path';
import _ from "lodash";
import jsonData  from './data/finalList.json'  assert { type: "json" };


let rootPath = "./en4/data/"
// 创建一个axios实例并设置全局请求头
const server = axios.create({
    baseURL: "https://api.cet6study.com/",
    headers: {
        'Host': 'api.cet6study.com',
        'Content-Type': 'application/json',
        'xweb_xhr': 1,
        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x6309080f)XWEB/8461",
        'Cookie': "cetSsId=CwZ7GEENt2tPtwjqD4prBfEHewpsXvQG",
    }
});

//最终需要请求的接口地址
let finalGrammarDetailList = []

const fetchWithDelay = async () => {
    try {


        finalGrammarDetailList = jsonData

        for (const {url, filePath} of finalGrammarDetailList) {

            let delayTime = _.random(1, 3, true)
            await delay(delayTime * 1000);
            console.log(`delay:${delayTime}s ，接口 ${url}   filePath:${filePath}`);

            const response = await server.get(url);
            saveJson(filePath, response.data)

        }
    } catch (error) {
        console.error('请求出错:', error);
    }
};

let reqGrammarGroup = (item) => {
    server.get('grammar/list.htm?version=v13&parentId=' + item.id)
        .then(response => {
            if (response.data.dataList) {
                response.data.dataList.forEach(data => {
                    reqGrammar(data)
                })
                saveJson(rootPath + "finalList.json", finalGrammarDetailList)
                // fetchWithDelay()
            }

        })
}


// 'grammar/list.htm?version=v13&grammarId=' + item.id
let reqGrammar = (item) => {
    finalGrammarDetailList.push({
        url: 'grammar/info.htm?version=v13&grammarId=' + item.id,
        filePath: rootPath + item.grammar + ".json"
    })

    // server.get('grammar/info.htm?version=v13&grammarId=' + item.id)
    //     .then(response => {
    //         saveJson(rootPath + item.grammar + ".json", response.data)
    //     })
}


let saveJson = (pathStr, data) => {

    let parts = pathStr.split('/');
    let parentPath = parts.slice(0, 3).join('/');

    if (!fs.existsSync(parentPath)) {
        fs.mkdirSync(parentPath, {recursive: true});
    }

    const filePath = path.join(parentPath, parts.slice(3,parts.length).join('/')
        .replaceAll("\""," ")
        .replaceAll("/"," ")
        .replaceAll(";"," ")

    ); // 构建文件路径

    fs.writeFileSync(filePath, JSON.stringify(data), 'utf-8');
}

let req = () => {
    server.get('grammar/list.htm?version=v13&parentId=0')
        .then(response => {
            saveJson(rootPath + '分组.json', response.data);

            if (response.data.dataList) {

                response.data.dataList.forEach((item, index) => {
                    reqGrammarGroup(item)
                })
            }
        })
        .catch(error => {
            console.error('Request error:', error);
        });
}



async  function  delay2(time){
    return  new Promise(resolve =>{
        setTimeout(resolve,time)
    } )
}
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// req()  //运行后 会生成finalList.json  里面包含最终请求的详情url 和对应要生成的path文件路径
fetchWithDelay() // 生成finalList.json后 运行！ 接口请求成功后  延迟1-3s 请求下一个接口 并 根据path保存文件